<template>
    <div class="leave-process">
        <!-- 查询表单 -->
        <a-form class="smart-query-form">
            <a-row class="smart-query-form-row">
                <a-form-item label="请假时间" class="smart-query-form-item">
                    <a-range-picker v-model:value="dateRange" :presets="defaultTimeRanges" @change="dateRangeChange" />
                </a-form-item>
                <a-form-item label="状态" class="smart-query-form-item">
                    <a-radio-group v-model:value="queryForm.state" buttonStyle="solid">
                        <a-radio-button :value="undefined">全部</a-radio-button>
                        <a-radio-button :value="0">待审核</a-radio-button>
                        <a-radio-button :value="1">已通过</a-radio-button>
                        <a-radio-button :value="2">已驳回</a-radio-button>
                    </a-radio-group>
                </a-form-item>
                <a-form-item class="smart-query-form-item smart-margin-left10">
                    <a-button-group>
                        <a-button type="primary" @click="onSearch">
                            <template #icon>
                                <SearchOutlined />
                            </template>
                            查询
                        </a-button>
                        <a-button @click="resetQuery">
                            <template #icon>
                                <ReloadOutlined />
                            </template>
                            重置
                        </a-button>
                    </a-button-group>
                </a-form-item>
            </a-row>
        </a-form>

        <!-- 表格区域 -->
        <a-card size="small" :bordered="false" :hoverable="true">
            <a-row class="smart-table-btn-block">
                <div class="smart-table-operate-block">
                    <a-button type="primary" @click="showLeaveModal()">
                        <template #icon>
                            <PlusOutlined />
                        </template>
                        新增请假
                    </a-button>
                    <a-button type="primary" @click="printLeave" v-if="selectedRecord">
                        <template #icon>
                            <PrinterOutlined />
                        </template>
                        打印请假条
                    </a-button>
                </div>
                <div class="smart-table-setting-block">
                    <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.leave.process"
                        :refresh="queryData" /> -->
                </div>
            </a-row>

            <!-- 请假列表 -->
            <a-table size="small" class="ant-table-striped" :columns="columns" :data-source="tableData"
                :loading="tableLoading" :pagination="false" rowKey="id" bordered :scroll="{ x: 1300 }"
                :row-className="(record, index) => (index % 2 === 1 ? 'table-striped' : null)">

                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'action'">
                        <a-button @click="showLeaveModal(record)" size="small" type="link">查看</a-button>
                        <a-button v-if="record.state === 0" @click="cancelLeave(record)" size="small" danger
                            type="link">撤销</a-button>
                    </template>
                    <template v-else-if="column.dataIndex === 'state'">
                        <a-tag v-if="record.state === 0" color="processing">待审核</a-tag>
                        <a-tag v-if="record.state === 1" color="success">已通过</a-tag>
                        <a-tag v-if="record.state === 2" color="error">已驳回</a-tag>
                    </template>
                    <template v-else-if="column.dataIndex === 'leaveStartTime' || column.dataIndex === 'leaveEndTime'">
                        {{ formatDate(record[column.dataIndex], 'YYYY-MM-DD HH:mm') }}
                    </template>
                    <template v-else-if="column.dataIndex === 'createTime'">
                        {{ formatDate(record.createTime, 'YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </template>
            </a-table>

         
        </a-card>

        <!-- 请假表单抽屉 -->
        <a-drawer v-model:open="drawerOpen" :title="drawerTitle" placement="right" width="600px"
            @close="closeDrawer">
            <a-form ref="leaveFormRef" :model="leaveForm" :rules="rules" :label-col="{ span: 6 }"
                :wrapper-col="{ span: 16 }">

                <a-form-item label="年级" name="grade" required>
                    <a-input v-model:value="leaveForm.grade" placeholder="请输入年级" />
                </a-form-item>

                <a-form-item label="专业" name="major" required>
                    <a-input v-model:value="leaveForm.major" placeholder="请输入专业" />
                </a-form-item>

                <a-form-item label="学员类型" name="studentType" required>
                    <a-select v-model:value="leaveForm.studentType">
                        <a-select-option value="1">本院</a-select-option>
                        <a-select-option value="2">委培</a-select-option>
                        <a-select-option value="3">社会化</a-select-option>
                        <a-select-option value="4">专硕</a-select-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="轮转科室" name="department" required>
                    <a-input v-model:value="leaveForm.department" placeholder="请输入当前轮转科室" />
                </a-form-item>

                <a-form-item label="请假时间" required>
                    <a-space>
                        <a-form-item name="leaveStartTime" :rules="[{ required: true, message: '请选择开始时间' }]" style="margin-bottom: 0">
                            <a-date-picker 
                                v-model:value="leaveForm.leaveStartTime"
                                show-time
                                format="YYYY-MM-DD HH:mm"
                                placeholder="开始时间" />
                        </a-form-item>
                        <span>至</span>
                        <a-form-item name="leaveEndTime" :rules="[{ required: true, message: '请选择结束时间' }]" style="margin-bottom: 0">
                            <a-date-picker 
                                v-model:value="leaveForm.leaveEndTime"
                                show-time
                                format="YYYY-MM-DD HH:mm"
                                placeholder="结束时间" />
                        </a-form-item>
                    </a-space>
                </a-form-item>

                <a-form-item label="请假原因" name="reason" required>
                    <a-textarea v-model:value="leaveForm.reason" :rows="4" placeholder="请输入请假原因" />
                </a-form-item>
            </a-form>

            <template #footer>
                <a-button style="margin-right: 8px" @click="closeDrawer">取消</a-button>
                <a-button type="primary" @click="submitLeave" :loading="submitLoading">提交</a-button>
            </template>
        </a-drawer>

        <!-- 打印模板 -->
        <div id="printSection" style="display: none;">
            <div class="print-content">
                <h2 style="text-align: center;">请假条</h2>
                <div class="print-body">
                    <p>本人是{{ selectedRecord?.grade }}级{{ selectedRecord?.major }}专业
                        （{{ getStudentTypeText(selectedRecord?.studentType) }}）学员，
                        现在{{ selectedRecord?.department }}科轮转，
                        因{{ selectedRecord?.reason }}，需要请假{{ getLeaveDays(selectedRecord) }}天
                        （{{ formatDate(selectedRecord?.leaveStartTime) }}至{{ formatDate(selectedRecord?.leaveEndTime)
                        }}），
                        望予以批准。</p>

                    <div class="sign-block">
                        <p>签名：________________</p>
                        <p>{{ formatDate(selectedRecord?.createTime, 'YYYY年MM月DD日') }}</p>
                    </div>

                    <div class="approve-block">
                        <p>带教老师签名：________________</p>
                        <p>科室主任签名：________________</p>
                        <p>导师签名（专硕）：________________</p>
                    </div>

                    <div class="divider">
                        ———————————————————————————————————————————
                    </div>

                    <div class="receipt">
                        <h3>请假回执（科室留存）</h3>
                        <p>{{ selectedRecord?.grade }}级{{ selectedRecord?.major }}专业
                            （{{ getStudentTypeText(selectedRecord?.studentType) }}）
                            学员{{ selectedRecord?.name }}请假{{ getLeaveDays(selectedRecord) }}天
                            （{{ formatDate(selectedRecord?.leaveStartTime) }}至{{
                                formatDate(selectedRecord?.leaveEndTime) }}），
                            已备案。</p>
                        <div class="education-sign">
                            <p>教育处</p>
                            <p>{{ formatDate(null, 'YYYY年MM月DD日') }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, PrinterOutlined } from '@ant-design/icons-vue';

import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { defaultTimeRanges } from '/@/lib/default-time-ranges';
import { smartSentry } from '/@/lib/smart-sentry';
import dayjs from 'dayjs';
import { Space as ASpace } from 'ant-design-vue';



const tableData = ref([

            {
                id: 1,
                state: '0',
                grade: '2023',
                major: '麻醉学',
                name: '张三',
                studentType: '1',
                department: '心胸外科',
                leaveStartTime: dayjs('2024-03-20 09:00:00'),
                leaveEndTime: dayjs('2024-03-22 17:00:00'),
                reason: '参学术会议',
                createTime: dayjs('2024-03-19 14:30:00')
            },
            {
                id: 2,
                state: '1',
                grade: '2023',
                major: '麻醉学',
                name: '李四',
                studentType: '2',
                department: '普外科',
                leaveStartTime: dayjs('2024-03-15 09:00:00'),
                leaveEndTime: dayjs('2024-03-16 17:00:00'),
                reason: '家中有事',
                createTime: dayjs('2024-03-14 10:20:00')
            },
            {
                id: 3,
                state: '2',
                grade: '2022',
                major: '麻醉学',
                name: '王五',
                studentType: '4',
                department: '骨科',
                leaveStartTime: dayjs('2024-03-10 09:00:00'),
                leaveEndTime: dayjs('2024-03-12 17:00:00'),
                reason: '身体不适',
                createTime: dayjs('2024-03-09 16:45:00')
            },
            {
                id: 4,
                state: '0',
                grade: '2023',
                major: '麻醉学',
                name: '赵六',
                studentType: '3',
                department: '神经外科',
                leaveStartTime: dayjs('2024-03-25 09:00:00'),
                leaveEndTime: dayjs('2024-03-26 17:00:00'),
                reason: '参加培训',
                createTime: dayjs('2024-03-24 11:20:00')
            },
            {
                id: 5,
                state: '1',
                grade: '2022',
                major: '麻醉学',
                name: '钱七',
                studentType: '1',
                department: '妇产科',
                leaveStartTime: dayjs('2024-03-18 09:00:00'),
                leaveEndTime: dayjs('2024-03-19 17:00:00'),
                reason: '家庭原因',
                createTime: dayjs('2024-03-17 09:15:00')
            }]
);
// 表格列定义
const columns = ref([
    {
        title: '状态',
        dataIndex: 'state',
        width: 80,
        fixed: 'left',
        align: 'center',
    },
    {
        title: '年级专业',
        dataIndex: 'gradeMajor',
        width: 120,
        align: 'center',
        customRender: ({ record }) => `${record.grade}级${record.major}`,
    },
    {
        title: '姓名',
        dataIndex: 'name',
        width: 100,
        align: 'center',
    },
    {
        title: '开始时间',
        dataIndex: 'leaveStartTime',
        width: 150,
        align: 'center',
    },
    {
        title: '结束时间',
        dataIndex: 'leaveEndTime',
        width: 150,
        align: 'center',
    },
    {
        title: '请假原因',
        dataIndex: 'reason',
        width: 200,
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 150,
        align: 'center',
    },
    {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        width: 120,
        align: 'center',
    },
]);

// 查询表单状态
const queryFormState = {
    startTime: null,
    endTime: null,
    state: undefined,
    pageNum: 1,
    pageSize: PAGE_SIZE,
};
const queryForm = reactive({ ...queryFormState });
const dateRange = ref(null);

// 表格数据
const tableLoading = ref(false);
const total = ref(0);

// 抽屉表单
const drawerOpen = ref(false);
const drawerTitle = ref('新增请假');
const leaveFormRef = ref();
const submitLoading = ref(false);

const leaveFormState = {
    id: undefined,
    grade: undefined,
    major: undefined,
    studentType: undefined,
    department: undefined,
    leaveStartTime: null,
    leaveEndTime: null,
    reason: undefined,
};
const leaveForm = reactive({ ...leaveFormState });

// 选中记录
const selectedRecord = ref(null);

// 表单校验规则
const rules = {
    grade: [{ required: true, message: '请输入年级' }],
    major: [{ required: true, message: '请输入专业' }],
    studentType: [{ required: true, message: '请选择学员类型' }],
    department: [{ required: true, message: '请输入轮转科室' }],
    reason: [{ required: true, message: '请填写请假原因' }],
};

// 日期范围变化
function dateRangeChange(dates) {
    if (dates) {
        queryForm.startTime = dates[0];
        queryForm.endTime = dates[1];
    } else {
        queryForm.startTime = null;
        queryForm.endTime = null;
    }
}

// 重置查询
function resetQuery() {
    dateRange.value = null;
    const pageSize = queryForm.pageSize;
    Object.assign(queryForm, queryFormState);
    queryForm.pageSize = pageSize;
    queryData();
}

// 搜索
function onSearch() {
    
    queryData();
}



// 查询数据
async function queryData() {
    tableLoading.value = true;
   
}

// 显示请假表单
function showLeaveModal(record) {
    drawerOpen.value = true;
    drawerTitle.value = record ? '查看请假' : '新增请假';
    // if (record) {
    //     Object.assign(leaveForm, record);
    //     selectedRecord.value = record;
    // } else {
    //     Object.assign(leaveForm, leaveFormState);
    //     selectedRecord.value = null;
    // }
}

// 关闭抽屉
function closeDrawer() {
    drawerOpen.value = false;
    leaveFormRef.value?.resetFields();
}

// 提交请假
async function submitLeave() {
    try {
        await leaveFormRef.value.validate();
        submitLoading.value = true;
        // TODO: 替换为实际的API调用
        // await leaveApi.submitLeave(leaveForm);
        message.success('提交成功');
        closeDrawer();
        queryData();
    } catch (e) {
        smartSentry.captureError(e);
    } finally {
        submitLoading.value = false;
    }
}

// 撤销请假
async function cancelLeave(record) {
    try {
        // TODO: 替换为实际的API调用
        // await leaveApi.cancelLeave(record.id);
        message.success('撤销成功');
        queryData();
    } catch (e) {
        smartSentry.captureError(e);
    }
}

// 获取学员类型文本
function getStudentTypeText(type) {
    const types = {
        '1': '本院',
        '2': '委培',
        '3': '社会化',
        '4': '专硕'
    };
    return types[type] || '';
}

// 格式化日期
function formatDate(date, format = 'MM月DD日') {
    if (!date) {
        return dayjs().format(format);
    }
    const d = typeof date === 'string' ? dayjs(date) : date;
    return d.format(format);
}

// 计算请假天数
function getLeaveDays(record) {
    if (!record?.leaveStartTime || !record?.leaveEndTime) {
        return 0;
    }
    const startTime = typeof record.leaveStartTime === 'string' ? dayjs(record.leaveStartTime) : record.leaveStartTime;
    const endTime = typeof record.leaveEndTime === 'string' ? dayjs(record.leaveEndTime) : record.leaveEndTime;
    return endTime.diff(startTime, 'day') + 1;
}

// 打印功能
function printLeave() {
    if (!selectedRecord.value) {
        message.warning('请先选择要打印的请假记录');
        return;
    }

    const printContent = document.getElementById('printSection').innerHTML;
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);

    iframe.contentDocument.write(`
        <html>
            <head>
                <style>
                    body { font-family: SimSun, serif; padding: 20px; }
                    .print-content { width: 21cm; margin: 0 auto; }
                    .print-body { line-height: 2; }
                    .sign-block { margin: 30px 0; text-align: right; }
                    .approve-block { margin: 30px 0; }
                    .approve-block p { margin: 15px 0; }
                    .divider { margin: 40px 0; text-align: center; }
                    .receipt { margin-top: 20px; }
                    .education-sign { margin-top: 30px; text-align: right; }
                    @media print {
                        @page { margin: 0.5cm; }
                    }
                </style>
            </head>
            <body>${printContent}</body>
        </html>
    `);

    iframe.contentWindow.print();

    setTimeout(() => {
        document.body.removeChild(iframe);
    }, 100);
}

onMounted(() => {
    queryData();
});
</script>

<style scoped>
.leave-process {
    padding: 24px;
}

.ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
}

@media print {
    .print-content {
        display: block !important;
    }
}
</style>